import React, { useEffect, useCallback } from 'react'
import style from './basic.scss'
import { mergeStyle } from './mergeStyle'

export const Input = ({ className, value, placeholder, type, onChange, onKeyDown, onClear, min, readOnly, title, showClear }) => {
    const [realValue, setRealValue] = React.useState(value)
    const wrapOnChange = React.useCallback(ev => {
        const value = ev.target.value
        setRealValue(value)
        typeof onChange === 'function' && onChange(value)
    }, [])

    useEffect(() => {
        setRealValue(value)
    }, [value])

    const onFocus = useCallback(ev => ev.target.select(), [])

    return (
        <React.Fragment>
            <input className={mergeStyle(style, 'basic_input', className)} value={realValue} placeholder={placeholder}
                min={min} type={type} onChange={wrapOnChange} readOnly={readOnly} onFocus={readOnly ? null : onFocus}
                title={title || realValue} onKeyDown={onKeyDown} />
            {showClear ? <span title='清空' className={mergeStyle(style, 'basic_input_clear')} onClick={onClear} ></span> : null}
        </React.Fragment>
    )
}